﻿using BaseUtils.Logger;
using DriveManage.SocketClient;
using Service.src.Model.Folw;
using Service.src.NW.Enum;
using Service.src.NW.Model;
using Service.src.NW.Model.Enum;
using Service.src.NW.Model.Folw;
using System.Net.Sockets;
using System.Text;

namespace Service.src.NW.Processor.Core
{
    public class SocketProcessor : BaseProcessor
    {
        // 定义一个具体的委托实例
        private static OnReceiveMsgHandler ClientMsgHandler;
        private static MessageReceivedEventHandler ServerMsgHandler;

        private static StringBuilder Buffer = new StringBuilder();

        internal static void Run(NodeProcessor nodeProcessor, NodeInputParam InputParam)
        {
            Buffer.Clear();
            if (!Assert(nodeProcessor))
            {
                return;
            }

            NodeSocketInputParam SocketInputParam = nodeProcessor.NodeInputParam.NodeSocket;
            ISocketHandler socket = AppData.SocketHandlers[SocketInputParam.DataSourceId];

            NodeDataSource SendMessage = GetNodeInputParam(nodeProcessor, SocketInputParam.SendMessage);

            string Val = SendMessage?.Value + "";
            if (!string.IsNullOrEmpty(Val))
            {
                socket.SendMessage(Val);
                SendNodeLoggerInfo(nodeProcessor, $"节点：{nodeProcessor.id}，发送数据={Val}");
            }

            if (SocketInputParam.IsWaitCallBack)
            {
                if (socket.Terminal == "client")
                {
                    ClientMsgHandler = new OnReceiveMsgHandler((scm, Message) => OnClientReceiveMsg(scm, Message, nodeProcessor));
                    socket.OnReceiveMsg -= ClientMsgHandler;
                    socket.OnReceiveMsg += ClientMsgHandler;
                }
                if (socket.Terminal == "server")
                {
                    ServerMsgHandler = new MessageReceivedEventHandler((SocketServerManager, scm, buffer, Message) => OnServerReceiveMsg(scm, Message, socket, nodeProcessor));
                    socket.OnMessageReceived -= ServerMsgHandler;
                    socket.OnMessageReceived += ServerMsgHandler;
                }
            }
            else
            {
                string Message = socket.ReceiveDataCache.ToString();
                SetNodeOutParamValue(nodeProcessor, NodeOutParamNameEnum.DEVICE_READ_RESULT, Message);
                Complete(nodeProcessor, NodeStatusEnum.SUCCESS);
            }
        }

        private static bool Assert(NodeProcessor nodeProcessor)
        {
            NodeSocketInputParam SocketInputParam = nodeProcessor?.NodeInputParam?.NodeSocket ?? null;

            if (SocketInputParam == null)
            {
                SendNodeLoggerWarning(nodeProcessor, $"节点配置异常，请检查节点的“配置管理”", RuntimeErrorCodeEnum.DEVICE_NOT_CONNECT);
                SetNodeOutParamValue(nodeProcessor, NodeOutParamNameEnum.NODE_STATUS, NodeStatusEnum.ERROR);
                Complete(nodeProcessor);
                return false;
            }

            if (!AppData.SocketHandlers.ContainsKey(SocketInputParam.DataSourceId))
            {
                SendNodeLoggerWarning(nodeProcessor, $"Scoket连接失败，请检查连接是否正常，配置信息 IP,端口等,正在尝试重连连接，请稍后重试 ", RuntimeErrorCodeEnum.DEVICE_NOT_CONNECT);
                SetNodeOutParamValue(nodeProcessor, NodeOutParamNameEnum.NODE_STATUS, NodeStatusEnum.ERROR);
                Complete(nodeProcessor);
                new AppData().StartDevice(SocketInputParam.DataSourceId);
                return false;
            }

            ISocketHandler socket = AppData.SocketHandlers[SocketInputParam.DataSourceId];
            if (socket == null || !socket.IsConnected)
            {
                SendNodeLoggerWarning(nodeProcessor, $"Scoket连接失败，请检查连接是否正常，配置信息 IP,端口等,正在尝试重连连接，请稍后重试 ", RuntimeErrorCodeEnum.DEVICE_NOT_CONNECT);
                SetNodeOutParamValue(nodeProcessor, NodeOutParamNameEnum.NODE_STATUS, NodeStatusEnum.ERROR);
                Complete(nodeProcessor);
                new AppData().StartDevice(SocketInputParam.DataSourceId);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 服务端收到消息
        /// </summary>
        /// <param name="scm"></param>
        /// <param name="Message"></param>
        /// <param name="socket"></param>
        /// <param name="Node"></param>
        private static void OnServerReceiveMsg(TcpClient scm, string Message, ISocketHandler socket, NodeProcessor Node)
        {
            socket.OnMessageReceived -= ServerMsgHandler;
            if (string.IsNullOrEmpty(Message))
            {
                return;
            }
            Buffer.AppendLine(Message);

            bool ec = true;
            NodeDataSource EndCharacter = Node?.NodeInputParam?.NodeSocket?.EndCharacter;
            EndCharacter = GetNodeInputParam(Node, EndCharacter);
            if (EndCharacter!=null
                && !Message.EndsWith(EndCharacter.Value))
            {
                ec = false;
                socket.OnMessageReceived += ServerMsgHandler;
            }
            if (ec)
            {
                string ResMsg = Buffer.ToString();
                SetNodeOutParamValue(Node, NodeOutParamNameEnum.DEVICE_READ_RESULT, ResMsg);
                LoggerService.Info($"回调信息：{ResMsg}");
                Complete(Node, NodeStatusEnum.SUCCESS);
            }
        }

        /// <summary>
        /// 客户端收到消息
        /// </summary>
        /// <param name="scm"></param>
        /// <param name="Message"></param>
        /// <param name="Node"></param>
        private static void OnClientReceiveMsg(SocketClientManager scm, string Message, NodeProcessor Node)
        {
            scm.OnReceiveMsg -= ClientMsgHandler;

            if (!string.IsNullOrEmpty(Message))
            {
                Message = Message.Trim();
                SetNodeOutParamValue(Node, NodeOutParamNameEnum.DEVICE_READ_RESULT, Message);
                LoggerService.Info($"回调信息：{Message}");
                Complete(Node, NodeStatusEnum.SUCCESS);
            }
        }
    }
}